index.js ➔ ... ➔ ???   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 1
nop 2
dl 0
loc 24
rs 9.65
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A ??? 0 11 4
1 View Code Duplication
'use strict';
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2
const pFinally = require('p-finally');
3
4
class TimeoutError extends Error {
5
	constructor(message) {
6
		super(message);
7
		this.name = 'TimeoutError';
8
	}
9
}
10
11
module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
12
	if (typeof ms !== 'number' || ms < 0) {
13
		throw new TypeError('Expected `ms` to be a positive number');
14
	}
15
16
	const timer = setTimeout(() => {
17
		if (typeof fallback === 'function') {
18
			resolve(fallback());
19
			return;
20
		}
21
22
		const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
23
		const err = fallback instanceof Error ? fallback : new TimeoutError(message);
24
25
		reject(err);
26
	}, ms);
27
28
	pFinally(
29
		promise.then(resolve, reject),
30
		() => {
31
			clearTimeout(timer);
32
		}
33
	);
34
});
35
36
module.exports.TimeoutError = TimeoutError;
37